import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Spin, Alert, Button, Typography, Tag, Rate, Image } from 'antd';
import { ReloadOutlined, ClearOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import recommendationService from '../../services/RecommendationService';
import { useNavigate, useLocation } from 'react-router-dom';
import '../../styles/MovieRecommend.css';

const { Title, Text } = Typography;

const PersonalizedRecommendation = () => {
  const [movies, setMovies] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [clearingCache, setClearingCache] = useState(false);
  const [lastPreferences, setLastPreferences] = useState(null);
  const [isTimeout, setIsTimeout] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();

  // 比较用户偏好是否发生变化
  const comparePreferences = (current, previous) => {
    if (!previous) return false; // 没有之前的偏好记录，需要重新获取
    
    // 比较关键偏好字段
    const keyFields = ['favorite_genres', 'favorite_actors', 'favorite_directors'];
    
    for (const field of keyFields) {
      const currentValue = current[field] || [];
      const previousValue = previous[field] || [];
      
      // 比较数组长度
      if (currentValue.length !== previousValue.length) {
        return false;
      }
      
      // 比较数组内容（排序后比较）
      const currentSorted = [...currentValue].sort();
      const previousSorted = [...previousValue].sort();
      
      if (JSON.stringify(currentSorted) !== JSON.stringify(previousSorted)) {
        return false;
      }
    }
    
    return true; // 偏好相同
  };

  // 创建超时Promise
  const createTimeoutPromise = (timeout) => {
    return new Promise((_, reject) => {
      setTimeout(() => {
        reject(new Error('TIMEOUT'));
      }, timeout);
    });
  };

  // 获取个性化推荐（带偏好检查和超时控制）
  const fetchPersonalizedRecommendations = async (forceRefresh = false) => {
    setLoading(true);
    setError(null);
    setIsTimeout(false);
    
    try {
      // 获取当前用户偏好
      const profileResult = await Promise.race([
        recommendationService.getUserProfileData(),
        createTimeoutPromise(45000) // 45秒超时
      ]);
      
      if (!profileResult.success) {
        setError('获取用户偏好失败');
        return;
      }
      
      const currentPreferences = profileResult.data;
      
      // 获取当前用户ID
      const userStr = localStorage.getItem('user');
      let userId = 'default';
      if (userStr) {
        try {
          const user = JSON.parse(userStr);
          userId = user.id;
        } catch (e) {
          console.warn('解析用户信息失败:', e);
        }
      }
      
      // 从localStorage获取上次的偏好和推荐数据（按用户ID区分）
      const cachedData = localStorage.getItem(`personalizedRecommendations_${userId}`);
      const cachedPreferences = localStorage.getItem(`lastUserPreferences_${userId}`);
      
      let shouldUseCache = false;
      
      if (!forceRefresh && cachedData && cachedPreferences) {
        try {
          const parsedCachedPreferences = JSON.parse(cachedPreferences);
          const parsedCachedData = JSON.parse(cachedData);
          
          // 检查偏好是否相同
          if (comparePreferences(currentPreferences, parsedCachedPreferences)) {
            // 偏好相同，使用缓存
            setMovies(parsedCachedData);
            setLastPreferences(currentPreferences);
            shouldUseCache = true;
            console.log(`使用用户 ${userId} 的缓存个性化推荐数据`);
          }
        } catch (e) {
          console.warn('解析缓存数据失败:', e);
        }
      }
      
      if (!shouldUseCache) {
        // 偏好发生变化或没有缓存，重新获取推荐
        console.log('偏好发生变化，重新获取个性化推荐');
        const result = await Promise.race([
          recommendationService.getPersonalizedRecommendations(),
          createTimeoutPromise(65000) // 65秒超时
        ]);
        
        if (result.success) {
          setMovies(result.data);
          setLastPreferences(currentPreferences);
          
          // 缓存新的推荐数据和偏好信息（按用户ID区分）
          localStorage.setItem(`personalizedRecommendations_${userId}`, JSON.stringify(result.data));
          localStorage.setItem(`lastUserPreferences_${userId}`, JSON.stringify(currentPreferences));
        } else {
          setError(result.message);
        }
      }
    } catch (err) {
      if (err.message === 'TIMEOUT') {
        setIsTimeout(true);
        setError('网络连接超时，请检查网络连接或设置代理后重试');
      } else {
        setError('获取个性化推荐失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  // 清除缓存并重新获取
  const handleClearCache = async () => {
    setClearingCache(true);
    
    try {
      // 获取当前用户ID
      const userStr = localStorage.getItem('user');
      let userId = 'default';
      if (userStr) {
        try {
          const user = JSON.parse(userStr);
          userId = user.id;
        } catch (e) {
          console.warn('解析用户信息失败:', e);
        }
      }
      
      // 清除后端缓存
      const result = await recommendationService.clearPersonalizedCache();
      if (result.success) {
        // 清除本地缓存（按用户ID区分）
        localStorage.removeItem(`personalizedRecommendations_${userId}`);
        localStorage.removeItem(`lastUserPreferences_${userId}`);
        setLastPreferences(null);
        
        // 强制重新获取推荐
        await fetchPersonalizedRecommendations(true);
      } else {
        setError(result.message);
      }
    } catch (err) {
      setError('清除缓存失败，请稍后重试');
    } finally {
      setClearingCache(false);
    }
  };

  // 组件挂载时获取推荐
  useEffect(() => {
    fetchPersonalizedRecommendations();
  }, []);

  // 监听路由变化，当用户返回到个性化推荐页面时检查偏好变化
  useEffect(() => {
    // 当路由变化到个性化推荐页面时，检查偏好是否发生变化
    if (location.pathname === '/recommendation/personalized') {
      fetchPersonalizedRecommendations();
    }
  }, [location.pathname]);

  // 渲染电影卡片
  const renderMovieCard = (movie) => {
    const isNoRating = movie.rating === 0 || movie.rating === null || movie.rating === undefined;
    const rating = isNoRating ? '暂无评分' : (typeof movie.rating === 'number' ? movie.rating.toFixed(1) : (isNaN(parseFloat(movie.rating)) ? '暂无评分' : parseFloat(movie.rating).toFixed(1)));

    return (
      <Col xs={24} sm={12} md={8} lg={6} key={movie.id} className="movie-recommend-col">
        <Card
          hoverable
          className="movie-recommend"
          cover={
            <div>
              <img src={movie.poster_url || '/placeholder-movie.jpg'} alt={movie.title} />
              <img
                src={movie.poster_url || '/placeholder-movie.jpg'}
                alt={movie.title}
                onClick={() => navigate(`/recommendation/movie-detail/${movie.id}?source=tmdb`)}
              />
            </div>
          }
          onClick={() => navigate(`/recommendation/movie-detail/${movie.id}?source=tmdb`)}
        >
          <Title level={5}>{movie.title}</Title>
          <div className="movie-recommend-movie-info">
            {isNoRating ? (
              <Text type="secondary">{rating}</Text>
            ) : (
              <div className="movie-recommend-rating">
                <Rate disabled allowHalf defaultValue={movie.rating / 2} />
                <Text strong>{rating}</Text>
              </div>
            )}
          </div>
          <Text type="secondary">
            {movie.year} · {movie.genre && movie.genre.length > 0 ? movie.genre.join(' / ') : (movie.genres && movie.genres.length > 0 ? movie.genres.join(' / ') : '未知类型')}
          </Text>
        </Card>
      </Col>
    );
  };

  return (
    <div className="movie-recommend">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <Button
          type="text"
          onClick={() => navigate(-1)}
          icon={<ArrowLeftOutlined />}
          className="movie-recommend-back-button"
        >
          返回
        </Button>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button
            icon={<ReloadOutlined />}
            onClick={() => fetchPersonalizedRecommendations(true)}
            loading={loading}
            className="movie-recommend-back-button"
          >
            刷新推荐
          </Button>
          <Button
            icon={<ClearOutlined />}
            onClick={handleClearCache}
            loading={clearingCache}
            className="movie-recommend-back-button"
          >
            清除缓存
          </Button>
        </div>
      </div>

      {error && (
        <Alert
          message={isTimeout ? "网络连接超时" : "获取推荐失败"}
          description={
            isTimeout ? (
              <div>
                <p>{error}</p>
                <div style={{ marginTop: 8 }}>
                  <strong>解决方案：</strong>
                  <ul style={{ marginTop: 4, paddingLeft: 20 }}>
                    <li>检查网络连接是否正常</li>
                    <li>如果在国内，建议设置代理访问TMDB API</li>
                    <li>可以尝试使用VPN或其他网络代理工具</li>
                    <li>稍后再试或联系管理员</li>
                  </ul>
                </div>
              </div>
            ) : error
          }
          type="error"
          showIcon
          closable
          onClose={() => {
            setError(null);
            setIsTimeout(false);
          }}
          style={{ marginBottom: 16 }}
        />
      )}

      {loading ? (
        <div className="movie-recommend-loading">
          <Spin size="large" tip="正在获取个性化推荐..." />
        </div>
      ) : error ? (
        <div className="movie-recommend-error">{error}</div>
      ) : movies.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '50px 0' }}>
          <Text type="secondary" style={{ fontSize: '24px' }}>
            暂无个性化推荐，请先在设置中完善您的偏好信息
          </Text>
        </div>
      ) : (
        <>
          <div style={{ marginBottom: 16, textAlign: 'center' }}>
            <Text type="secondary" style={{ fontSize: '18px' }}>
              根据您的喜好为您推荐了 {movies.length} 部电影
            </Text>
            {lastPreferences && (
              <div style={{ marginTop: 8 }}>
                <Text type="secondary" style={{ fontSize: '18px' }}>
                  💡 智能缓存已启用，偏好未变化时将快速加载
                </Text>
              </div>
            )}
          </div>
          <Row gutter={[16, 16]}>{movies.map(renderMovieCard)}</Row>
        </>
      )}
    </div>
  );
};

export default PersonalizedRecommendation;